/*----------------------------------------
Preset Values
----------------------------------------*/
var aniSpeed = {slow: 2000, med: 1000, fast: 500, flash: 200};
/*----------------------------------------
Functions
----------------------------------------*/
//trim
function trim(str) {
	var str = str.replace(/^\s\s*/, ''),
	ws = /\s/,
	i = str.length;
	while (ws.test(str.charAt(--i))){}
	return str.slice(0, i + 1);
}
//has
function has(key, obj) {
	var i;
	for(i in obj) if(obj[i] == key) return true;
	return false;
}
//auiAjax
var auiAjax = {
	request: {},
	send: function(name, opt, des) {
		this.abort(name);
		this.request[name] = {des: des, body: $.ajax(opt)};
		return this.request[name].body;
	},
	abort: function(name) {
		if(this.request[name] != null) this.request[name].body.abort();
	}
};
//set input tips
function initInput() {
	$('input[type=text],textarea').each(function(){
		/*if(!$(this).attr('tips') || $(this).attr('tips') == '') return;
		$(this).focus(function(){
			if($(this).val() == $(this).attr('tips')) $(this).val('').removeClass('inputTips');
			$(this).focus();
		});
		$(this).blur(function(){
			if($(this).val() == '' || $(this).val() == $(this).attr('tips')) $(this).val($(this).attr('tips')).addClass('inputTips');
			else $(this).removeClass('inputTips');
		});
		if($(this).val() == '' || $(this).val() == $(this).attr('tips')) $(this).focusout();*/
	});
}
$.fn.selectRange = function(start, end) {
	return this.each(function() {
		if (this.setSelectionRange) {
			this.focus();
			this.setSelectionRange(start, end);
		} else if (this.createTextRange) {
			var range = this.createTextRange();
			range.collapse(true);
			range.moveEnd('character', end);
			range.moveStart('character', start);
			range.select();
		}
	});
};
/*----------------------------------------
 * 说明：javascript的加减乘除结果会有误差，这个函数返回较为精确的结果。		
 ----------------------------------------*/
//除法函数
//用法：accDiv(arg1,arg2)
//@return arg1除以arg2的精确结果
//@remark 本函数压缩后可能出现t1、t2未初始化问题
function accDiv(arg1,arg2){
	var t1=0,t2=0,r1,r2;
	try{t1=arg1.toString().split(".")[1].length;}catch(e){}
	try{t2=arg2.toString().split(".")[1].length;}catch(e){}
	//debugger;
	with(Math){
		r1=Number(arg1.toString().replace(".",""));
		r2=Number(arg2.toString().replace(".",""));
		return (r1/r2)*pow(10,t2-t1);
	}
}
//乘法函数
function accMul(arg1,arg2){
	var m=0,s1=arg1.toString(),s2=arg2.toString();
	try{m+=s1.split(".")[1].length;}catch(e){}
	try{m+=s2.split(".")[1].length;}catch(e){}
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
//加法函数
function accAdd(arg1,arg2){
	var r1,r2,m;
	try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
	try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
	m=Math.pow(10,Math.max(r1,r2));
	return (arg1*m+arg2*m)/m;
}
//减法函数
function accSub(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
    try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
    m=Math.pow(10,Math.max(r1,r2));
    //动态控制精度长度
    n=(r1>=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
}
//js中的toFixed方法也有精度问题
Number.prototype.toFixed=function(len){
	var add = 0,s;
	var s1 = this + "";
	var start = s1.indexOf(".");
	if(s1.substr(start+len+1,1)>=5){add=1;}
	var temp = Math.pow(10,len);
	s = Math.floor(this * temp) + add;
	return s/temp;
};
/*----------------------------------------
Init
----------------------------------------*/
$(document).ready(function() {
	//init input
	initInput();
	initSearchBar();
	feedback.init();
	initChgLocation();
	initPopup();
	bannerSearch.init();
	$(window).scroll(function(e){
		if($(window).scrollTop() > 100) $('#backtotop').show();
		else $('#backtotop').hide();
	});
	goToLogin();
});

function initSearchBar() {
	$('.searchBar form input').keypress(function(e){
		if(e.keyCode == 13) $('.searchBar form').submit();
	});
	$('#search_submit').click(function(){$('.searchBar form').submit();});
	$('.searchBar form').submit(function(){
		$(this).find('.inputTips').val('');
	});
}

function initChgLocation() {
	$('#changeLocation').click(function(){
		$('#locationPop').show().focus();
	});
	$('#locationPop').blur(function(){
		$(this).fadeOut(aniSpeed.flash);
	});
	var str = $.cookie('flymealAddress');
	if(str != null){
		var obj = eval('(' + str + ')');
          for(var i = 0; i < (obj.pguidList.length-1); i++){
        	  $('#locationPop ul').prepend('<li><a class="blink" href="' + getRootPath() + '/area/'+obj.pguidList[i] + '">'+ obj.addressList[i] +'</a></li>');
          }
			  $('.location [name=def]').html(obj.addressList[(obj.pguidList.length-1)]);
	}
}

function initPopup() {
	//if($.browser.msie && $.browser.version < 7) $('.pop .mask').css('height', $(document).height()+'px');
	$('.pop .close').click(function(){$(this).parent().parent().hide();});
}

var feedback = {
		isLogin: typeof(ISLOGIN) == 'undefined' ? false : ISLOGIN,
		init: function(){
			$('#feedback_btn').click(function(){
				feedback.isLogin = $('#loginHref').length > 0 ? false: true;
				$('#feedback_pop [name^=step_]').hide();
				$('.tip').hide();
				$('#feedback_pop [name=step_1]').show();
				var t = $(document).scrollTop()+$(window).height()/2-150;
				$('#feedback_pop .c').css('top', t+'px');
				$('#feedback_pop').show();
				if($('#feedback_pop [name=content]').hasClass('inputTips')) $('#feedback_pop .type li:first').click();
			});
			$('#feedback_pop .type li').click(function(){
				$('#feedback_pop .type li').removeClass('active');
				$(this).addClass('active');
				var t = $(this).attr('t');
				var content = $('#feedback_pop [name=content]');
				content.attr('tips', $(this).attr('tips')).removeClass('s');
				if(content.hasClass('inputTips')) content.val('').focusout();
				$('#feedback_pop .rest_name, #feedback_pop .report_type').hide();
				if(t == 3) {
					$('#feedback_pop .rest_name').show();
					content.addClass('s');
				}
				else if(t == 4) {
					$('#feedback_pop .report_type').show();
					content.addClass('s');
				}
			});
			$('#feedback_pop .submit').click(function(){
				var wrong = false;
				$('#feedback_pop [name=step_1] :input:visible').each(function(){
					if(trim($(this).val()) == '' || $(this).hasClass('inputTips')) {
						alert('请填写完整必要内容。');
						wrong = true;
						return false;
					}
				});
				if(wrong) return;
				if(feedback.isLogin) feedback.submit();
				else if($('#feedback_pop [name=step_1]').css('display') == 'none') {
					var uname = $('#feedback_pop [name=uname]');
					var upassword = $('#feedback_pop [name=upassword]');
					var uemail = $('#feedback_pop [name=uemail]');
					if((uname.val() == '' || upassword.val() == '' || uname.hasClass('inputTips') || upassword.hasClass('inputTips')) && (uemail.val() == '' || uemail.hasClass('inputTips'))) {
						alert('请至少选择一种方式。');
						return;
					}
					feedback.submit(uname.val(), upassword.val(), uemail.val());
				}
				else {
					$('#feedback_pop [name^=step_]').hide();
					$('#feedback_pop [name=step_2]').show();
					//if($.browser.msie && $.browser.version < 7) $('#feedback_pop .tel').hide().show();
				}
			});
		},
		submit: function(uname, upassword, uemail) {
			$('#feedback_pop [name^=step_]').hide();
			var params = {
				t: 0,
				q_cat: $('#feedback_pop .type .active').attr("t"),
				q_content: $('#feedback_pop [name=content]').val(),
				q_report_type:null,
				q_report_id:0,
				q_rest_name:null,
				uname:null,
				upassword:null,
				uemail:null
			};
			var report_type = $('#feedback_pop [name=report_type]').val();
			var report_id = $('#feedback_pop [name=report_id]').val();
			var rest_name = $('#feedback_pop input[name=rest_name]').val();
			var page_rest_name = $("#companyName").val();
			if(report_type != '') params.q_report_type = report_type;
			if(report_id != '') params.q_report_id = report_id;
			if(rest_name != '') {
				params.q_rest_name = rest_name;
			} else {
				params.q_rest_name = page_rest_name;
			}
			if(!feedback.isLogin) {
				if(uname != '' && upassword != '') {
					params.t = 1;
					params.uname = uname;
					params.upassword = upassword;
				}
				else {
					params.t = 2;
					params.uemail = uemail;
				}
			}
			$.ajax({
		        url : getRootPath()+'/customerajax/feedbackinfo!addFeedback.action',
		        data: params,
		        cache : false, 
		        async : true,
		        type : "POST",
		        dataType : 'json',
		        beforeSend	: function(xmlHttpRequest){
		        	$('#feedback_pop [name=step_3]').show();
				},
		        success : function (data){
		        	$('#feedback_pop [name=step_3]').hide();
		        	feedback.done(data);
		        },
		        error	:	function(){
		        	$('#feedback_pop [name=step_5]').show();
		        }
		    });
		},
		done: function(d) {
			if(d.errorCode != '') {	
				$('#feedback_pop [name=step_2]').show();
				$('.tip').show();
				return;
			}
			$('#feedback_pop [name^=step_]').hide();
			$('#feedback_pop [name=step_4]').show();
			if((d.q_cat == 3)&&(d.t == 0||d.t == 1)){
				pointsPop.gen(20, '#feedback_pop [name=step_4] .alertText');
			}
			$('#feedback_pop .type li').removeClass('active');
			$('#feedback_pop .type li:first').addClass('active');
			$('#feedback_pop [name=content]').val('').focusout();
			$('#feedback_pop [name=uname]').val('').focusout();
			$('#feedback_pop [name=upassword]').val('');
			$('#feedback_pop [name=uemail]').val('').focusout();
		}
	};

var pointsPop = {
		gen: function(p, ele) {
			if($(ele).attr('pointsAdded') == 1) return;
			$(ele).attr('pointsAdded', 1);
			var offset = $(ele).offset();
			var p = $('<div class="pointsPop">+'+p+' 积分</div>');
			$('body').append(p);
			p.css({left: offset.left+'px', top: (offset.top-10)+'px'}).animate({opacity: 1, top: (offset.top-30)+'px'}, aniSpeed.fast, function(){
				$(this).animate({opacity: 0}, 3000, 'easeInExpo', function(){$(this).remove();});
			});
		}
	};
var bannerSearch = {
	init: function() {
		$('#search_submit').click(bannerSearch.submit);
	},
	submit: function() {
		var product = $(this).parent().find(".place");
		var zone = $(this).parent().find(".restaurant");
		if(product.val() == product.attr('tips')) {
			product.val('');
		}
		if(zone.val() == zone.attr('tips')) {
			zone.val('');
		}
		$(this).parent().submit();
	}
};


//登陆后跳回到登录前的页面
function goToLogin(){
	var root = getRootPath();
	var str = top.window.location.href;
	//剥离前面的跟目录，目的是为struts跳转传参
	str = str.substring(root.length, str.length);
	if(str.indexOf("backUrl") > 0 ){//已经包含了backurl，则不再包含
		$('#loginHref').attr('href', getRootPath()  + str);
	}else{
		if(str.indexOf("#")>0){
			//剥离最后的#
			str = str.substring(0, str.length-1);
		}
		if(str.indexOf("/customer/login!login.action") >= 0) {
			str = "/";
		}
		var url = escape(str);
		url = url.replace(/\//g,"%2F");
		$('#loginHref').attr('href', getRootPath() + "/customer/login!login.action?backUrl=" + url);
	}
};


var loadingArea = {
		attach: function(dom) {
			var loadingEle = $('<div class="loadingArea"></div>');
			$(dom).append(loadingEle);
		},
		remove: function(dom) {
			$(dom).find('.loadingArea').remove();
		}
};

var dialog = {
		counter: 0,
		create: function(opt) {
			opt.id = dialog.counter++;
			if(opt.type != 'confirm') opt.type = 'alert';
			if(!opt.text) opt.text = '';
			if(!opt.text_ok) opt.text_ok = '确定';
			if(!opt.text_cancel) opt.text_cancel = '取消';
			if(!opt.data) opt.data = null;
			var d = $(new EJS({url: getRootPath()+'/assets/ejs/dialog.ejs'}).render(opt));
			d.find('[name=ok]').bind('click', {ok: opt.ok, data: opt.data}, function(e){
				var p = $(this).parents('.pop');
				p.remove();
				if(typeof e.data.ok != 'undefined') e.data.ok.call(p, e.data.data);
			});
			d.find('[name=cancel]').bind('click', {cancel: opt.cancel, data: opt.data}, function(e){
				var p = $(this).parents('.pop');
				p.remove();
				if(typeof e.data.cancel != 'undefined') e.data.cancel.call(p, e.data.data);
			});
			//*if($.browser.msie && $.browser.version < 7) d.find('.mask').css('height', $(document).height()+'px');
			var t = $(document).scrollTop()+$(window).height()/2-60;
			d.find('.c').css('top', t+'px');
			d.appendTo('body').show();
		}
	};

function getRootPath(){
	return window.location.protocol+'//'+window.location.host;	
}

//日期转化为字符串格式： yyyy-mm-dd
function DateToStr(dt){
	return dt.substr(0, 10);
} 


//载入模板
function require_template(templateName) {
    var template = $('#template_' + templateName);
    
    if (template.length === 0) {
        var tmpl_dir = '/assets/templates';
        var tmpl_url = tmpl_dir + '/' + templateName + '.tmpl';
        var tmpl_string = '';

        $.ajax({
            url: tmpl_url,
            method: 'post',
            dataType : 'html',
            async: false,
            contentType: 'html',
            success: function (data) {
                tmpl_string = data;
            }
        });
        
      
        $('head').append('<script id="template_' + 
        templateName + '" type="text/template">' + tmpl_string + '<\/script>');
    }
}




String.prototype.trim = function(){ 
	return Trim(this);	
}
	
function LTrim(str)
{
    var i;
    for(i=0;i<str.length;i++)
    {
        if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break;
    }
    str=str.substring(i,str.length);
    return str;
}
function RTrim(str)
{
    var i;
    for(i=str.length-1;i>=0;i--)
    {
        if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break;
    }
    str=str.substring(0,i+1);
    return str;
}
function Trim(str)
{
    return LTrim(RTrim(str));
}



/**
 * 清理价格小数点后的0, 比如 15.00 -> 15, 15.50 -> 15.5
 */
String.prototype.trimPrice = function(){ 
	return this.replace(/\.?0*$/,'');	
}
